package com.css.bjdt_core.reportFill.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.css.bjdt_core.cell.dao.CellDataDao;
import com.css.bjdt_core.cell.entity.CellData;
import com.css.bjdt_core.cell.entity.VarParam;
import com.css.bjdt_core.cell.service.CellDataService;
import com.css.bjdt_core.cell.service.CustomSqlService;
import com.css.bjdt_core.reportFill.entity.RptFillHistoryEntity;
import com.css.bjdt_core.util.CommonUtil;
import com.css.bjdt_core.util.ReportConstant;

//报表填报历史
@Service
public class ReportReturnDifferenceService extends CustomSqlService {

	@Autowired
	private Dao dao;

	@Autowired
	private CellDataService cellDataService;

	@Autowired
	private CellDataDao cellDataDao;

	/**
	 * 动态创建表
	 * 
	 * @param annualId
	 */
	public void createTable(String annualId) {
		String tableName = ReportConstant.FILL_HISTORY_TABLE_PREFIX + annualId;
		String count = executeSql(ReportConstant.ISEXIST_TABLE_SQL, Sqls.callback.str(),
				new VarParam(null, null, "table_name", tableName)).getString();
		if ("0".equals(count)) {
			executeSql(ReportConstant.FILL_HISTORY_CREATE_TABLE_SQL, null,
					new VarParam("table_name", tableName, null, null));
		}
	}

	/**
	 * 现在和历史数据对比，然后不一样的入库
	 * 
	 * @param annualId
	 * @param fillCellDataList  填报的数据
	 * @param dzzId
	 * @param templateId
	 */

	public void saveFillHistoryCellValue(String annualId, List<CellData> fillCellDataList, String dzzId,
			String templateId) {
		createTable(annualId);
		//先获取该张报表的数据库中的指标值
		List<CellData> cellDataListHistory = cellDataDao.selectCellData(annualId, dzzId, templateId, null, "1000", "1");
		//将该报表中的数据转换成MAP
		Map<String, CellData> cellDataMapHistory = new HashMap<String, CellData>();
		for (CellData cellData : cellDataListHistory) {
			String key = cellData.getAbsRowNum() + "--" + cellData.getAbsColNum();
			cellDataMapHistory.put(key, cellData);
		}
		//填报历史记录List
		List<RptFillHistoryEntity> rptFillHistoryEntityList = new ArrayList<RptFillHistoryEntity>();
		for (CellData fillCellData : fillCellDataList) {
			if (!fillCellData.getCellType().equals("1") && !fillCellData.getCellType().equals("2")
					&& !fillCellData.getCellType().equals("3")) {
				continue;
			}
			CellData historyCellData = cellDataMapHistory
					.get(fillCellData.getAbsRowNum() + "--" + fillCellData.getAbsColNum());
			if (historyCellData == null) {
				historyCellData = new CellData();
				historyCellData.setCellValue("0");
			}
			if (!fillCellData.getCellValue().equals(historyCellData.getCellValue())) {
				RptFillHistoryEntity rptFillHistoryEntity = new RptFillHistoryEntity();
				rptFillHistoryEntity.setId(CommonUtil.getUUID());
				rptFillHistoryEntity.setCellId(fillCellData.getCellId());
				rptFillHistoryEntity.setDzzId(dzzId);
				rptFillHistoryEntity.setTemplateId(templateId);
				rptFillHistoryEntity.setCellValue(fillCellData.getCellValue());
				rptFillHistoryEntity.setHistoryCellValue(historyCellData.getCellValue());
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
				Date date = new Date();
				rptFillHistoryEntity.setUpdateTime(df.format(new Date()));
				rptFillHistoryEntity.setAbsRowNum(fillCellData.getAbsRowNum() + "");
				rptFillHistoryEntity.setAbsColNum(fillCellData.getAbsColNum() + "");
				rptFillHistoryEntity.setRelRowNum(fillCellData.getRelRowNum() + "");
				rptFillHistoryEntity.setRelColNum(fillCellData.getRelColNum() + "");
				rptFillHistoryEntityList.add(rptFillHistoryEntity);
			}
		}
		insertRptFillHistory(annualId, rptFillHistoryEntityList);
	}

	public void insertRptFillHistory(String annualId, List<RptFillHistoryEntity> rptFillHistoryEntityList) {
		String tableName = ReportConstant.FILL_HISTORY_TABLE_PREFIX + annualId.toUpperCase();
		if (rptFillHistoryEntityList != null && rptFillHistoryEntityList.size() > 0) {
			List<List<RptFillHistoryEntity>> lists = CommonUtil.subList(rptFillHistoryEntityList, 40);
			List<Sql> sqls = new ArrayList<Sql>();
			for (List<RptFillHistoryEntity> list : lists) {
				StringBuilder batchInsertCellValueSql = new StringBuilder();
				batchInsertCellValueSql.append("INSERT ALL ");

				for (RptFillHistoryEntity rptFillHistoryEntity : list) {
					batchInsertCellValueSql.append("INTO ").append(tableName).append(" VALUES (")
							.append(addQuotesStr(rptFillHistoryEntity.getId())).append(",")
							.append(addQuotesStr(rptFillHistoryEntity.getCellId())).append(",")
							.append(addQuotesStr(rptFillHistoryEntity.getDzzId())).append(",")
							.append(addQuotesStr(rptFillHistoryEntity.getTemplateId())).append(",")
							.append(addQuotesStr(rptFillHistoryEntity.getCellValue())).append(",")
							.append(addQuotesStr(rptFillHistoryEntity.getHistoryCellValue())).append(",")
							.append(addQuotesStr(rptFillHistoryEntity.getUpdateTime())).append(",")
							.append(addQuotesStr(rptFillHistoryEntity.getAbsRowNum())).append(",")
							.append(addQuotesStr(rptFillHistoryEntity.getAbsColNum())).append(",")
							.append(addQuotesStr(rptFillHistoryEntity.getRelRowNum())).append(",")
							.append(addQuotesStr(rptFillHistoryEntity.getRelColNum())).append(")  ");
				}
				batchInsertCellValueSql.append(" SELECT * FROM dual");
				try {
					Sql batchInsertsql = Sqls.create(batchInsertCellValueSql.toString());
					sqls.add(batchInsertsql);
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
			dao.execute(sqls.toArray(new Sql[0]));
		}
	}

	//加个单引号给传进来的字符串（专门为数据汇总批量插入方法）
	public String addQuotesStr(String str) {
		return "'" + str + "'";
	}
}
